package io.renren.modules.sys.controller;

import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.common.validator.group.UpdateGroup;
import io.renren.modules.sys.entity.JxCourseScheduleEntity;
import io.renren.modules.sys.entity.JxLaboratoryEntity;
import io.renren.modules.sys.entity.JxStudentEntity;
import io.renren.modules.sys.entity.JxStudentScheduleEntity;
import io.renren.modules.sys.service.JxCourseScheduleService;
import io.renren.modules.sys.service.JxLaboratoryService;
import io.renren.modules.sys.service.JxStudentScheduleService;
import io.renren.modules.sys.service.JxStudentService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.DecimalFormat;
import java.util.*;


/**
 * 受教日程
 *
 * @author Mark
 * @email sunlightcs@gmail.com
 * @date 2021-10-19 14:23:25
 */
@RestController
@RequestMapping("sys/jxstudentschedule")
public class JxStudentScheduleController {
    @Autowired
    private JxStudentScheduleService jxStudentScheduleService;

    @Autowired
    private JxCourseScheduleService jxCourseScheduleService;   // 课程安排

    @Autowired
    private JxStudentService jxStudentService;   //  学生

    @Autowired
    private JxLaboratoryService jxLaboratoryService; //  实验室


    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("sys:jxstudentschedule:list")
    public R list(@RequestParam Map<String, Object> params) {

        PageUtils page = jxStudentScheduleService.getAllWithPage(params);
        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("sys:jxstudentschedule:info")
    public R info(@PathVariable("id") Long id) {
        JxStudentScheduleEntity jxStudentSchedule = jxStudentScheduleService.getById(id);

        return R.ok().put("jxStudentSchedule", jxStudentSchedule);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("sys:jxstudentschedule:save")
    public R save(@RequestBody JxStudentScheduleEntity jxStudentSchedule) {
        ValidatorUtils.validateEntity(jxStudentSchedule,AddGroup.class);
        jxStudentScheduleService.save(jxStudentSchedule);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("sys:jxstudentschedule:update")
    public R update(@RequestBody JxStudentScheduleEntity jxStudentSchedule) {
        if(jxStudentSchedule.getUseDeviceId()>0) {
            ValidatorUtils.validateEntity(jxStudentSchedule, UpdateGroup.class);
            DecimalFormat df = new DecimalFormat("#.00");
            /***  旧 的数据   **/

            JxStudentScheduleEntity old = jxStudentScheduleService.getById(jxStudentSchedule.getId());   //  之前的数据
            Long oldCourseScheduleId = old.getCourseScheduleId();  // 之前的使用率
            JxCourseScheduleEntity oldCourseSchedule = jxCourseScheduleService.getById(oldCourseScheduleId);
            JxLaboratoryEntity laboratoryEntity = jxLaboratoryService.getById(oldCourseSchedule.getLaboratoryId());
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("courseScheduleId", oldCourseSchedule.getId());
            List<JxStudentScheduleEntity> list = jxStudentScheduleService.getList(params); //  所有使用的设备数据
            Double rate = Double.valueOf(list.size() - 1) / Double.valueOf(laboratoryEntity.getDeviceSize());
            rate = Double.valueOf(df.format(rate));
            oldCourseSchedule.setUsageRate(rate);
            jxCourseScheduleService.updateById(oldCourseSchedule);

            /** 新数据 ***/
            JxCourseScheduleEntity newCourseSchedule = jxCourseScheduleService.getById(jxStudentSchedule.getCourseScheduleId());
            JxLaboratoryEntity laboratory = jxLaboratoryService.getById(newCourseSchedule.getLaboratoryId());
            params.put("courseScheduleId", newCourseSchedule.getId());
            List<JxStudentScheduleEntity> list1 = jxStudentScheduleService.getList(params); //  所有使用的设备数据
            Double rate1 = Double.valueOf(Double.valueOf(list1.size() + 1) / Double.valueOf(laboratory.getDeviceSize()));
            rate1 = Double.valueOf(df.format(rate1));
            newCourseSchedule.setUsageRate(rate1);
            jxCourseScheduleService.updateById(newCourseSchedule);

            jxStudentScheduleService.updateById(jxStudentSchedule);
        }else{
            return R.error("请选择合适的设备");
        }

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("sys:jxstudentschedule:delete")
    public R delete(@RequestBody Long[] ids) {
        jxStudentScheduleService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    /***
     * 拿到剩余未分配实验设备的学生// 同一个班级
     * @param params
     * @return
     */
    @RequestMapping("/lastStudent")
    public R getLastStudent(@RequestParam Map<String, Object> params) {
        List<JxCourseScheduleEntity> courseSchedules = jxCourseScheduleService.getListByPo(params); //
        params.put("ids", 0);
        if (courseSchedules.size() > 0) {
            String ids = "";
            for (int i = 0; i < courseSchedules.size(); i++) {
                if (i == 0) {
                    ids = ids + courseSchedules.get(0).getId();
                } else {
                    ids = ids + "," + courseSchedules.get(i).getId();
                }
            }
            params.put("ids", ids);
        }
        List<JxStudentScheduleEntity> studentSchedules = jxStudentScheduleService.allocatedStudentIds(params);
        params.put("ids", 0);
        if (studentSchedules.size() > 0) {
            String ids = "";
            for (int i = 0; i < studentSchedules.size(); i++) {
                if (i == 0) {
                    ids = ids + studentSchedules.get(0).getId();
                } else {
                    ids = ids + "," + studentSchedules.get(i).getId();
                }
            }
            params.put("ids", ids);
        }
        List<JxStudentEntity> entities = jxStudentService.getLastStudents(params);

        return R.ok().put("data", entities);
    }


    /**
     * 提交分配的数据
     */
    @RequestMapping("/submit")
    public R sunbData(@RequestBody List<JxStudentScheduleEntity> dataList) {
        try {
            JxStudentScheduleEntity entity = dataList.get(0);
            Long laboratoryId = entity.getLaboratoryId();
            JxLaboratoryEntity laboratory = jxLaboratoryService.getById(laboratoryId);
            JxCourseScheduleEntity courseSchedule = jxCourseScheduleService.getById(entity.getCourseScheduleId());
            List<JxStudentScheduleEntity> list=new ArrayList<JxStudentScheduleEntity>();
            for(JxStudentScheduleEntity en:dataList){
                if(null!=en.getStudentId()){
                   list.add(en);
                }
            }

            if (laboratory.getDeviceSize() > 0) {
                if(list.size()>0) {
                    jxStudentScheduleService.addBatchStudentSchedule(list);
                    courseSchedule.setStatus("1");  // 已经被分配完
                    Double len1 = Double.valueOf(list.size());
                    Double len2 = Double.valueOf(laboratory.getDeviceSize());
                    Double rate = len1 / len2;
                    DecimalFormat df = new DecimalFormat("#.00");
                    rate = Double.valueOf(df.format(rate));
                    courseSchedule.setUsageRate(rate);
                    jxCourseScheduleService.saveOrUpdate(courseSchedule);
                }else{
                    return  R.error().put("msg","请选择要分配的班级！");
                }
            }else{
                return  R.error().put("msg","实验室没有设备！");
            }
        } catch (Exception e) {
            return R.error();
        }
        return R.ok();
    }


    @RequestMapping("listByPo")
    public R listByPo(@RequestParam Map<String, Object> params){
       List<JxStudentScheduleEntity> list= jxStudentScheduleService.getList(params);
       return R.ok().put("data",list);
    }

}
